//
//  UIImagePickerController+Block.m
//  NEW-ZHUKE
//
//  Created by 陈浩 on 16/11/1.
//  Copyright © 2016年 beelieve. All rights reserved.
//

#import "UIImagePickerController+Block.h"
#import <objc/runtime.h>

static char kBlock;
static char kTag;


@implementation UIImagePickerController (Block)

- (void)dealloc{
#if DEBUG
    NSLog(@"imagepicker dealloc");
#endif
}

- (instancetype)initWithSourceType:(UIImagePickerControllerSourceType)sourceType finish:(void(^)(UIImagePickerController *vc,UIImage *image)) selectImageBlock{
    self = [self init];
    if (self) {
        self.delegate = self;
        //摄像头
        self.sourceType = sourceType;
        self.selectImageBlock = selectImageBlock;
    }
    return self;
}


- (void)setSelectImageBlock:(void (^)(UIImagePickerController *vc,UIImage *))selectImageBlock{
    objc_setAssociatedObject(self, &kBlock, selectImageBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void)setTag:(NSInteger)tag{
    objc_setAssociatedObject(self, &kTag, @(tag), OBJC_ASSOCIATION_ASSIGN);

}

- (void (^)(UIImagePickerController *vc,UIImage *))selectImageBlock{
    return objc_getAssociatedObject(self, &kBlock);
}

- (NSInteger)tag{
    NSNumber *numValue = objc_getAssociatedObject(self, &kTag);
    return numValue.integerValue;
}

#pragma mark  - UIImagePickerControllerDelegate -

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo{
    UIImage * im=[editingInfo valueForKey:UIImagePickerControllerOriginalImage];
    
    if (self.selectImageBlock) {
        self.selectImageBlock(self, im);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *im = info[UIImagePickerControllerOriginalImage];
    
    if (self.selectImageBlock) {
        self.selectImageBlock(self, im);
    }

    [self dismissViewControllerAnimated:YES completion:nil];
}




@end
